unit INamedDevice;

interface
uses
{$IFDEF MSWINDOWS}
  Windows,
{$ENDIF}
  SysUtils,
  IPollThread,
  idata;

type
  EOXMLEvent = procedure (Value: EOIOBuffer) of object;
  EOStringEvent = procedure (Value: EOIOBuffer) of object;
  EOCharEvent = procedure (Value: EOIOBuffer) of object;

  EOINamedDevice = class
  private
    // ip:port
    FDeviceName: String;
    FIP: String;
    FPort: String;

    FActive: Integer;

    FOnXMLEvent: EOXMLEvent;
    FOnStringEvent: EOStringEvent;
    FOnCharEvent: EOCharEvent;

    procedure setActive(Value: Boolean);
    function getActive: Boolean;

  protected
    FDataIn: EOIOBuffer;
    FDataOut: EOIOBuffer;

    procedure doOpen; virtual; abstract;
    procedure doClose; virtual; abstract;

  public
    FDataInLock, FDataOutLock: Integer;

    Busy: Integer;

    property DeviceName: String read FDeviceName;
    property DeviceIP: String read FIP;
    property DevicePort: String read FPort;
    property Active: Boolean read getActive write setActive;
    property DataIn: EOIOBuffer read FDataIn;
    property DataOut: EOIOBuffer read FDataOut;

    property OnXMLEvent: EOXMLEvent read FOnXMLEvent write FOnXMLEvent;
    property OnStringEvent: EOStringEvent read FOnStringEvent write FOnStringEvent;
    property OnCharEvent: EOCharEvent read FOnCharEvent write FOnCharEvent;

    //function Read(Data: EOIOBuffer): Boolean; virtual; abstract;
    //function Write(Data: EOIOBuffer): Boolean; virtual; abstract;

    procedure AddThread(ThreadInstance: Longint); virtual;
    procedure RemoveThread(ThreadInstance: EOIPollThread); virtual;

    constructor Create(Name: String);

  end;

implementation

procedure EOINamedDevice.setActive(Value: Boolean);
var
  tmpA: Integer;
begin
  if Value then begin
    if FActive = 0 then begin
      tmpA := 1;
      InterlockedExchange(FActive, tmpA);

      // open a connection
      doOpen;
    end;
  end
  else begin
    if FActive <> 0 then begin
      tmpA := 0;
      InterlockedExchange(FActive, tmpA);

      // close connection(s)
      doClose;
    end;
  end;
end;

function EOINamedDevice.getActive: Boolean;
begin
  if FActive > 0 then
    Result := True
  else
    Result := False;
end;

procedure EOINamedDevice.AddThread(ThreadInstance: Longint);
begin
end;

procedure EOINamedDevice.RemoveThread(ThreadInstance: EOIPollThread);
begin
end;

constructor EOINamedDevice.Create(Name: String);
begin
  FDeviceName   := Name;
  FIP           := Copy(FDeviceName, 1, Pos(':', FDeviceName)-1);
  FPort         := Copy(FDeviceName, Pos(':', FDeviceName) + 1, Length(FDeviceName)-Pos(':', FDeviceName));
  FDataIn       := EOIOBuffer.Create;
  FDataOut      := EOIOBuffer.Create;
  FActive       := 0;
  FDataInLock   := 0;
  FDataOutLock  := 0;

  Busy          := 0;

  Active        := True;
end;

end.

